<template>
    <!-- Main content -->
    <div>
        <div class="row">
            <div class="col-xs-12">
                <theme-box title="电子券广告列表">
                    <form class="form-inline" @submit.prevent v-el:form>
                        <form-select title="商户名称" :sreach="true" :up-table="true" :options="mchtList"
                                     name="mchtId"></form-select>

                        <button type="reset" @click="reset" class="btn btn-warning pull-right">重置</button>
                        <v-button theme="primary" @click="search" class="pull-right">查询</v-button>
                    </form>
                    <table class="table table-bordered table-striped" style="width:100%" v-el:table>
                    </table>
                </theme-box>
            </div>
            <!-- /.col -->
        </div>
        <modal-container title="修改" v-el:modal v-ref:modal class="edit-modal revise-body" theme="big">
            <form @submit.prevent @reset.prevent v-el:mform>
                <div class="modal-body">
                    <table-modal :item="item" :columns-set="columnsSet"></table-modal>
                </div>

                <div class="modal-footer">
                    <v-button data-dismiss="modal" @click="resetBindDrag">关闭</v-button>
                    <v-button theme="primary" type="submit">保存</v-button>
                </div>
            </form>
        </modal-container>
        <!-- /.row -->
    </div>
    <!-- /.content -->
</template>

<style lang="less" scoped>
    .form-inline .btn + .btn {
        margin-right: 10px;
    }

    .form-inline .form-group + .form-group {
        margin-left: 20px;
    }
</style>
<script>
    import {
        dateTime,
        createDataTable
    } from 'ui/collections/general.js'
    var serialize = require('form-serialize');
    import {dateFormat} from "lib/method.js"

    var dataTable;
    var columnsSet;
    export default {
        data: () => ({
            item: {},
            columnsSet: [],
            mchtList:[]
        }),
        methods: {
            //还原弹出框位置
            resetBindDrag () {
                console.log(this.item)
                this.$refs.modal._resetBindDrag();
            },
            //查询按钮
            search: function () {
                dataTable.ajax.reload();
            },
            //重置按钮
            reset: function () {
                $(".form-inline")[0].reset();
                dataTable.ajax.reload();
            },
            getMcht (data) {
                let self = this;
                var mchtId = JSON.parse(localStorage.getItem("id_token")).mchtId
                self.$post({
                    url: "/api/v2" + projectName_Url + "/list/mcht/" + mchtId,
                    method: "GET"
                }).then(response => {
                    let list = response.content.info;
                    if (list.length == 1) {
                        list.unshift({key: "商户", value: ""});
                        self.$set("mchtList", list);
                    } else {
                        list.unshift({key: "所有商户", value: ""});
                        self.$set("mchtList", list);
                        self.mchtIdValue = list[0].value
                    }
                }, error => {
                });
            }
        },
        created() {
            //datatable所用数组
            columnsSet = [{
                title: "广告号",
                data: "banId",
                visible:false,
                className: "operate"
            },{
                title: "商户号",
                data: "mchtId",
                className: "operate",
                visible:false
            },{
                title: "商户名称",
                data: "mchtName",
                edit:true,
                readonly:true,
                className: "operate"
            },{
                title: "电子券号",
                data: "couponId",
                visible:false,
                className: "operate"
            },{
                title: "电子券名称",
                data: "couponName",
                edit:true,
                readonly:true,
                className: "operate"
            },{
                title: "名称",
                data: "name",
                edit: true,
                className: "operate",
                className:'wrap'
            }, {
                title: "图片",
                data: "file",
                upload:true,
                img: true,
                className: "operate",
                render: function (data) {
                    return `<img class="table-avatar" src=` + data + `>`
                }
            },{
                title: "最后修改时间",
                data: "lastTime",
                className: "operate",
                render: function (data) {
                    return dateFormat(data)
                }
            }, {
                title: "相关操作",
                className: "operate",
                width: "160px",
                render: function (value, type, row) {
                        return `
                            <button type="button" class="btn btn-primary btn-sm edit">修改</button>
                            <button type="button" class="btn btn-danger btn-sm delete">删除</button>
                        `
                }
            }]
        },
        ready: async function () {
            $(".dataTable img").css({"width": "50px", "height": "50px"});
            this.$set("columnsSet", columnsSet)
            var self = this;
            self.getMcht();
            dataTable = $(this.$els.table).DataTable({
                "columns": this.columnsSet, //定义列
                "ajax": async function (data, callback, settings) {
                    var page = [{
                        "name": "iDisplayStart",
                        "value": 1 + data.start / data.length
                    }, {
                        "name": "iDisplayLength",
                        "value": data.length
                    }];
                    //表单序列化数据
                    var _data = serialize(self.$els.form, {
                        hash: true,
                        disabled: true,
                        empty: true
                    });
                    _data.aoData = JSON.stringify(page);
                    //发送请求
                    var mchtId = JSON.parse(localStorage.getItem("id_token")).mchtId
                    var result = await self.$post({
                        url: "/api/v2" + projectName_Url + "/plat/couponBanner/query/" + mchtId,
                        data: _data,
                        method: "POST"
                    })
                    if (result.respCode != "00") {
                        Midway.alert({
                            title: "操作失败",
                            content: result.content
                        })
                    }
                    callback({
                        recordsTotal: result.content.total,
                        recordsFiltered: result.content.total,
                        data: result.content.list || []
                    })
                }
            });

            $(self.$el).on("click", ".edit", function () {
                var Row = $(this).closest('tr').get(0);
                const dataArray = JSON.parse(JSON.stringify(dataTable.row(Row).data()));
                self.item = dataArray;
                // //点击关闭 文件名称清空
                $(".modal-footer .btn.btn-default").click(function(){
                    $(".modal-body tbody tr:nth-child(2) td:nth-child(4) input").val('');
                })

                $(".modal-header .close span").click(function(){
                    $(".modal-body tbody tr:nth-child(2) td:nth-child(4) input").val('');
                });
                //编辑框验证、保存、提交
                $(self.$els.mform).validate(self.item.valdate = {
                    async submitHandler() {
                        var form = self.$els.mform;
                        let formData = new FormData(form)
                        formData.append("mchtId", self.item.mchtId)
                        formData.append("couponId", self.item.couponId)
                        var result = await self.$post({
                            url: "/api/v2" + projectName_Url + "/plat/couponBanner/" + self.item.banId,
                            data: formData,
                            method: "post"
                        });
                        Midway.alert({title: "操作提示", content: result.errorInfo})

                        dataTable.ajax.reload(null, false);
                        $(self.$els.modal).modal('hide');
                        self.resetBindDrag()
                    },
                    errorPlacement: function (error, element) {
                        if (element.attr("name") == "file") {
                            error.insertAfter(".file-item");
                        } else {
                            error.insertAfter(element)
                        }
                    },
                    rules: {
                        mchtId:{
                            required: true,
                        },
                        couponId:{
                            required: true,
                        },
                        name: {
                            required: true,
                            maxlength:25
                        },
                    }
                });
                $(self.$els.modal).modal('show');
            });

            $(self.$el).on("click", ".delete", async function () {
                var Row = $(this).closest('tr').get(0);
                var name = dataTable.row(Row).data().name;
                var id = dataTable.row(Row).data().banId;

                await Midway.confirm({
                    title: "删除电子券广告",
                    content: "是否要删除广告:" + name + "?"
                })
                var result = await self.$post({
                    url: "/api/v2" + projectName_Url + "/plat/couponBanner/" + id,
                    method: "DELETE"
                });
                Midway.alert({title: "操作提示", content: result.errorInfo})
                dataTable.ajax.reload();
            });
        },
        beforeDestroy() {
            $(this.$el).off("click")
        }
    }
</script>
